using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Terra.Core.Common.ApiResponse;
using Terra.Core.Common.ErrorCodes.Constants;
using Terra.Core.Common.Models.Common;
using Terra.Core.Common.Models.Pagination;
using Terra.Core.Common.Utils;
using Terra.Data.Entities.Identity;
using Terra.Data.Extensions;
using Terra.Data.Models.Identity;
using Terra.Data.Repository.Identity;
using Terra.Data.UnitOfWork;
using Terra.Service.Common.Base;
using Terra.Service.Identity.Interfaces;

namespace Terra.Service.Identity.Implementations
{
    /// <summary>
    /// 部门服务实现
    /// </summary>
    public class DeptService : AppServiceBase, IDeptService
    {
        private readonly IDeptRepository _deptRepository;
        private readonly IUserRepository _userRepository;
        private readonly ILogger<DeptService> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="unitOfWork">工作单元</param>
        /// <param name="deptRepository">部门仓储</param>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public DeptService(
            IUnitOfWork unitOfWork,
            IDeptRepository deptRepository,
            IUserRepository userRepository,
            IMapper mapper,
            ILogger<DeptService> logger) : base(unitOfWork, mapper)
        {
            _deptRepository = deptRepository ?? throw new ArgumentNullException(nameof(deptRepository));
            _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        #region 查询操作

        /// <inheritdoc/>
        public async Task<ApiResponse<DeptDetailDto>> GetDeptByIdAsync(Guid id)
        {
            var dept = await _deptRepository.GetByIdAsync(id);
            if (dept == null)
            {
                return ApiResponse<DeptDetailDto>.Error(SecurityErrorCodes.DEPT_NOT_FOUND);
            }

            var dto = Mapper.Map<DeptDetailDto>(dept);

            // 填充关联信息
            if (dept.ParentId.HasValue)
            {
                var parent = await _deptRepository.GetByIdAsync(dept.ParentId.Value);
                if (parent != null)
                {
                    dto.ParentName = parent.Name;
                }
            }

            // 填充部门负责人信息
            if (dept.LeaderId.HasValue)
            {
                var leader = await _userRepository.GetByIdAsync(dept.LeaderId.Value);
                if (leader != null)
                {
                    dto.LeaderName = leader.UserName;
                }
            }

            return ApiResponse<DeptDetailDto>.Success(dto);
        }

        /// <inheritdoc/>
        public async Task<ApiResponse<List<DeptTreeDto>>> GetDeptTreeAsync(int? status = 1)
        {
            var deptList = await _deptRepository.GetDeptTreeDataAsync(status);
            if (deptList == null || !deptList.Any())
            {
                return ApiResponse<List<DeptTreeDto>>.Success(new List<DeptTreeDto>());
            }

            // 映射为 DTO
            var deptDtos = Mapper.Map<List<DeptTreeDto>>(deptList);

            // 使用TreeUtils构建树结构
            var tree = TreeUtils.BuildTree(
                deptDtos,
                d => d.Id,
                d => d.ParentId,
                d => d.Children);

            return ApiResponse<List<DeptTreeDto>>.Success(tree);
        }

        /// <inheritdoc/>
        public async Task<ApiResponse<List<DeptSelectDto>>> GetDeptSelectsAsync(int? status = 1)
        {
            var deptList = await _deptRepository.GetDeptSelectDataAsync(status);
            if (deptList == null || !deptList.Any())
            {
                return ApiResponse<List<DeptSelectDto>>.Success(new List<DeptSelectDto>());
            }

            var deptSelectDtos = Mapper.Map<List<DeptSelectDto>>(deptList);
            return ApiResponse<List<DeptSelectDto>>.Success(deptSelectDtos);
        }

        /// <inheritdoc/>
        public async Task<ApiResponse<PagedList<DeptItemDto>>> GetPagedDeptsAsync(DeptQueryDto queryDto)
        {
            if (queryDto == null)
            {
                queryDto = new DeptQueryDto();
            }

            // 构建基础查询
            var query = _deptRepository.GetQueryable();

            // 应用过滤条件
            if (!string.IsNullOrWhiteSpace(queryDto.Name))
            {
                query = query.Where(d => d.Name.Contains(queryDto.Name));
            }

            if (!string.IsNullOrWhiteSpace(queryDto.Code))
            {
                query = query.Where(d => d.Code.Contains(queryDto.Code));
            }

            if (queryDto.Status.HasValue)
            {
                query = query.Where(d => d.Status == queryDto.Status.Value);
            }

            if (queryDto.ParentId.HasValue)
            {
                // 是否包含所有层级的子部门
                if (queryDto.IncludeAllLevels.HasValue && queryDto.IncludeAllLevels.Value)
                {
                    // 先获取指定父部门及其所有子部门的ID
                    var deptIds = await _deptRepository.GetDeptAndChildrenIdsAsync(queryDto.ParentId.Value);
                    query = query.Where(d => deptIds.Contains(d.Id));
                }
                else
                {
                    // 只查询直接子部门
                    query = query.Where(d => d.ParentId == queryDto.ParentId.Value);
                }
            }

            // 获取总数
            var totalCount = await query.CountAsync();
            if (totalCount == 0)
            {
                var emptyResult = new PagedList<DeptItemDto>(
                    new List<DeptItemDto>(),
                    0,
                    queryDto.PageIndex,
                    queryDto.PageSize);
                return ApiResponse<PagedList<DeptItemDto>>.Success(emptyResult);
            }

            // 应用排序和分页
            var orderBy = !string.IsNullOrEmpty(queryDto.OrderBy) ? queryDto.OrderBy : nameof(Dept.Sort);
            var isAsc = !queryDto.IsDescending;
            query = query.ApplyOrder(orderBy, !isAsc);
            query = query.Skip((queryDto.PageIndex - 1) * queryDto.PageSize).Take(queryDto.PageSize);

            // 执行查询
            var items = await query.ToListAsync();
            var deptDtos = Mapper.Map<List<DeptItemDto>>(items);

            // 填充关联信息
            foreach (var dto in deptDtos)
            {
                if (dto.ParentId.HasValue)
                {
                    var parent = items.FirstOrDefault(d => d.Id == dto.ParentId.Value);
                    if (parent != null)
                    {
                        dto.ParentName = parent.Name;
                    }
                }

                if (dto.LeaderId.HasValue)
                {
                    // 这里可以进一步优化，批量查询负责人信息
                    var leader = await _userRepository.GetByIdAsync(dto.LeaderId.Value);
                    if (leader != null)
                    {
                        dto.LeaderName = leader.UserName;
                    }
                }
            }

            var result = new PagedList<DeptItemDto>(
                deptDtos,
                totalCount,
                queryDto.PageIndex,
                queryDto.PageSize);
            return ApiResponse<PagedList<DeptItemDto>>.Success(result);
        }

        #endregion

        #region 业务操作

        /// <inheritdoc/>
        public async Task<ApiResponse<Guid>> CreateDeptAsync(DeptCreateDto dto)
        {
            // 验证部门名称唯一性
            if (await _deptRepository.ExistsByNameAsync(dto.Name))
            {
                return ApiResponse<Guid>.Error(SecurityErrorCodes.DEPT_NAME_ALREADY_EXISTS);
            }

            // 验证部门编码唯一性
            if (!string.IsNullOrWhiteSpace(dto.Code) && await _deptRepository.ExistsByCodeAsync(dto.Code))
            {
                return ApiResponse<Guid>.Error(SecurityErrorCodes.DEPT_CODE_ALREADY_EXISTS);
            }

            // 验证父部门存在
            if (dto.ParentId.HasValue)
            {
                var parentDept = await _deptRepository.GetByIdAsync(dto.ParentId.Value);
                if (parentDept == null)
                {
                    return ApiResponse<Guid>.Error(SecurityErrorCodes.PARENT_DEPT_NOT_FOUND);
                }
            }

            // 实体映射
            var dept = Mapper.Map<Dept>(dto);

            // 执行创建
            dept = await _deptRepository.InsertAsync(dept);

            // 更新部门路径
            await _deptRepository.UpdateDeptPathAsync(dept.Id);

            return ApiResponse<Guid>.Success(dept.Id, "创建部门成功");
        }

        /// <inheritdoc/>
        public async Task<ApiResponse> UpdateDeptAsync(Guid id, DeptUpdateDto dto)
        {
            // 检查部门是否存在
            var dept = await _deptRepository.GetByIdAsync(id);
            if (dept == null)
            {
                return ApiResponse.Error(SecurityErrorCodes.DEPT_NOT_FOUND);
            }

            // 设置ID
            dto.Id = id;

            // 验证部门名称唯一性
            if (await _deptRepository.ExistsByNameAsync(dto.Name, dto.Id))
            {
                return ApiResponse.Error(SecurityErrorCodes.DEPT_NAME_ALREADY_EXISTS);
            }

            // 验证部门编码唯一性
            if (!string.IsNullOrWhiteSpace(dto.Code) && await _deptRepository.ExistsByCodeAsync(dto.Code, dto.Id))
            {
                return ApiResponse.Error(SecurityErrorCodes.DEPT_CODE_ALREADY_EXISTS);
            }

            // 验证父部门存在
            if (dto.ParentId.HasValue)
            {
                // 不能将自己设为父部门
                if (dto.ParentId.Value == dto.Id)
                {
                    return ApiResponse.Error(SecurityErrorCodes.CANNOT_SET_SELF_AS_PARENT_DEPT);
                }

                var parentDept = await _deptRepository.GetByIdAsync(dto.ParentId.Value);
                if (parentDept == null)
                {
                    return ApiResponse.Error(SecurityErrorCodes.PARENT_DEPT_NOT_FOUND);
                }

                // 检查是否形成循环依赖
                var childDeptIds = await _deptRepository.GetDeptAndChildrenIdsAsync(dto.Id);
                if (childDeptIds.Contains(dto.ParentId.Value))
                {
                    return ApiResponse.Error(SecurityErrorCodes.DEPT_CIRCULAR_DEPENDENCY);
                }
            }

            // 更新部门信息
            Mapper.Map(dto, dept);
            dept.LastModifiedTime = DateTime.UtcNow;

            // 执行更新
            await _deptRepository.UpdateAsync(dept);

            // 如果父部门变更，则更新路径
            if (dto.ParentId != dept.ParentId)
            {
                await _deptRepository.UpdateDeptPathAsync(dept.Id);
            }

            return ApiResponse.Success("更新部门成功");
        }

        /// <inheritdoc/>
        public async Task<ApiResponse> DeleteDeptAsync(Guid id)
        {
            // 检查部门是否存在
            var dept = await _deptRepository.GetByIdAsync(id);
            if (dept == null)
            {
                return ApiResponse.Error(SecurityErrorCodes.DEPT_NOT_FOUND);
            }

            // 检查是否存在子部门
            if (await _deptRepository.HasChildrenAsync(id))
            {
                return ApiResponse.Error(SecurityErrorCodes.DEPT_HAS_CHILDREN);
            }

            // // // TODO：待用户关联表创建完毕再开发 检查是否存在关联用户 - 使用用户仓储查询
            // // 检查是否存在关联用户 - 使用用户仓储查询
            // if (await _userRepository.ExistsAsync(u => u.DeptId == id))
            // {
            //     return ApiResponse.Error(SecurityErrorCodes.DEPT_HAS_USERS);
            // }

            // 执行删除
            await _deptRepository.DeleteByIdAsync(id);

            return ApiResponse.Success("删除部门成功");
        }

        /// <inheritdoc/>
        public async Task<ApiResponse> UpdateDeptStatusAsync(Guid id, int status)
        {
            // 检查部门是否存在
            var dept = await _deptRepository.GetByIdAsync(id);
            if (dept == null)
            {
                return ApiResponse.Error(SecurityErrorCodes.DEPT_NOT_FOUND);
            }

            // 更新状态
            dept.Status = status;
            dept.LastModifiedTime = DateTime.UtcNow;

            await _deptRepository.UpdateAsync(dept);

            return ApiResponse.Success("更新部门状态成功");
        }

        /// <inheritdoc/>
        public async Task<ApiResponse<BatchOperationResult>> BatchDeleteDeptsAsync(List<Guid> ids)
        {
            if (ids == null || !ids.Any())
            {
                return ApiResponse<BatchOperationResult>.Success(BatchOperationResult.Create(0, 0));
            }

            var successIds = new List<Guid>();
            var failedIds = new List<Guid>();

            foreach (var id in ids)
            {
                // 检查部门是否存在
                var dept = await _deptRepository.GetByIdAsync(id);
                if (dept == null)
                {
                    failedIds.Add(id);
                    continue;
                }

                // 检查是否存在子部门
                if (await _deptRepository.HasChildrenAsync(id))
                {
                    failedIds.Add(id);
                    continue;
                }

                // // TODO：待用户关联表创建完毕再开发 检查是否存在关联用户 - 使用用户仓储查询
                // if (await _userRepository.ExistsAsync(u => u.DeptId == id))
                // {
                //     failedIds.Add(id);
                //     continue;
                // }

                // 执行删除
                var deleteResult = await _deptRepository.DeleteByIdAsync(id);
                if (deleteResult)
                {
                    successIds.Add(id);
                }
                else
                {
                    failedIds.Add(id);
                }
            }

            var operationResult = BatchOperationResult.Create(successIds.Count, failedIds.Count, failedIds);
            return ApiResponse<BatchOperationResult>.Success(operationResult, "批量删除部门完成");
        }

        #endregion
    }
}